package dayu.controller;

import dayu.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author dayu
 * @create 2018/12/12 14:59
 * @Description
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/regist")
    public String regist(String loginName, String password) {
        System.out.println("===========UserController.regist===========");
        userService.regist(loginName, password);
        return "login";
    }
    @RequestMapping("/login")
    public String login(String loginName, String password, Model model) {
        System.out.println("===========UserController.login===========");
        System.out.println("loginName="+loginName+",pwd="+password);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        try {
            subject.login(token);
            return "forward:/product/findAll";
        }catch (UnknownAccountException e){
            System.out.println("未知的账号："+e.getMessage());
            model.addAttribute("errorMsg","未知账号");
        }catch (IncorrectCredentialsException e){
            model.addAttribute("errorMsg","账号密码错误");
            System.out.println("账号密码错误："+e.getMessage());
        }catch (AuthenticationException e){
            model.addAttribute("errorMsg","认证异常");
            System.out.println("认证异常："+e.getMessage());
            e.printStackTrace();
        }

        return "login";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
